<?php include 'header.php'; ?>
<script>
	//<![CDATA[
	var currentLocation;
	var day_add = '0';
	var req;
	
	var latitude = <?=$_GET['latitude']==null?'37.552224':$_GET['latitude']?>;
	var longitude = <?=$_GET['longitude']==null?'126.923311':$_GET['longitude']?>;
	var time = new Date().getHours();
	if (time % 2 == 1)
		time -= 1;
	
	var sortType = 'T';
	var performances = [];
	
	initHotspot();
	function initHotspot()
	{
		var url = "http://gilstar.com/gilstar/Performance.jsp";
		var obj = new Object();
		obj.req = "GET_HOTSPOT_LIST";
		req = obj.req;
		
		getJSON(url, obj);
	}

	function initList() {
		getPerformanceListForMap();
		
		if(Modernizr.geolocation)	//geolocation support check
		{
			//navigator.geolocation.getCurrentPosition(showList, handleError, {enableHighAccuracy : true, maximumAge : 75000});
		}
		else
		{
			alert("위치정보 서비스가 지원되지 않습니다.");
		}
	}

	function hotSpot(spot)
	{
		if (spot == 'my')
		{
			initList();	
		}
		else
		{
			latitude = spot.split(',')[0];
			longitude = spot.split(',')[1];

			getPerformanceListForMap();
		}
	}
	function showList(position)
	{
		latitude = position.coords.latitude;	//십진법 각도
		longitude = position.coords.longitude;	//십진법 각도.
		
		console.log(latitude + ' / ' + longitude);
		getPerformanceListForMap();
	}
	
	function handleError(err)
	{
		var code = err.code;
		//code의 종류에 1번은 사용자가 위치정보를 공유안함, 2번은 네트워크에 문제 발생, 3번은 시간이 너무 오래 걸림
		//4번은 알 수 없는 오류 발생.
		var message = err.message;		//최종 사용자를 위한 용도가 아님. 
		
	}
	
	function getJSON(url, json)
	{
		var requestStr = JSON.stringify(json, replacer);
		console.log(requestStr);
		
		$.ajax(
			{
				url: url,
				data: requestStr,
				type: "POST",
				success: function(data)
				{
					var resultObject = jQuery.parseJSON(data);
					jsonResponseHandler(resultObject);
				},
				fail: function(data)
				{
					alert(data);
				}
			});
	}
	
	function jsonResponseHandler(result)
	{
		if(result.ResultCode == -1)			//처리 도중 실패.
		{
			alert(result.ResultMessage);
		}
		else if(result.ResultCode == 0)	//성공적으로 처리 완료.
		{
			if (req == 'GET_PERFORMANCE_FROM_LIST') {
				performances = result.ResultMethod;	//access by array index.
				performances = []
				for(var nIndex = 0; nIndex < result.ResultMethod.length; nIndex++) {
					performance = result.ResultMethod[nIndex];
					latitudeAmount = latitude - performance.latitude;
					if (latitudeAmount < 0)
						latitudeAmount = -latitudeAmount;
					longitudeAmount = longitude - performance.longitude;
					if (longitudeAmount < 0)
						longitudeAmount = -longitudeAmount;
					performance.distance = latitudeAmount
					performances[nIndex] = performance;
				}
				sort(sortType);
			} else if (req == 'GET_HOTSPOT_LIST') {
				var selectBox = document.getElementById('setLocation');
				selectBox.length = 0;
				selectBox.options[0] = new Option('내 위치', 'my');
				for(var nIndex = 0; nIndex < result.ResultMethod.length; nIndex++) {
					spot = result.ResultMethod[nIndex];	//access by array index.
					selectBox.options[nIndex+1] = new Option(spot.name, (spot.latitude + ',' + spot.longitude));
				}
				initList();
			}
		}
	}
	
	function sort(type)
	{
		sortType = type;
		if (sortType == 'T') {
			document.getElementById('listOrder').className = 'listOrder listOrderSelTime';
		} else {
			document.getElementById('listOrder').className = 'listOrder listOrderSelDistance';
		}
		for (var i=0; i<performances.length-1; i++) {
			for (var j=i+1; j<performances.length; j++) {
				iPerformance = performances[i];
				jPerformance = performances[j];
				
				var swap = false;
				if (sortType == 'T') {
					if (iPerformance.time > jPerformance.time)
						swap = true;
				} else {
					if (iPerformance.distance < jPerformance.distance)
						swap = true;
				}
				if (swap) {
					performances[i] = jPerformance;
					performances[j] = iPerformance;
					break;
				}
			}
		}
		
		showPerformanceList();
	}
	function showPerformanceList()
	{
		if (performances.length == 0) {
			document.getElementById('listUl').innerHTML = '';
			document.getElementById('listUl').style.display = 'none';
			document.getElementById('listEmpty').style.display = '';
		} else {
			var html = '';
			for(var performance in performances) {
				performance = performances[performance];
				html +='<li class="listLi">';
				html +='	<a href="view.php?performance_seq='+performance.performance_seq+'" class="listA">';
				html +='		<div class="listThumbWrap">';
				if (performance.file != '') {
					html +='		<img src="/'+performance.file+'" alt="10cm" width="72" height="72" class="listThumb">';
				}
				html +='		</div>';
				html +='		<div class="listContent">';
				html +='			<h3 class="listH">'+performance.title+' <span class="listDiv">|</span> <span class="listArtist">'+performance.artist+'</span></h3>';
				html +='			<div class="listType">'+categories[performance.category]+'</div>';
				html +='			<div class="listTime">';
				times = performance.time.split(' ')[1].split(':');
				html +='				<time datetime="'+performance.time+'">' + times[0]+':'+times[1] + ' ~</time>';
				html +='			</div>';
				html +='			<div class="listLoc">'+performance.address+'</div>';
				html +='		</div>';
				html +='	</a>';
	            html +='</li>';
			}
			document.getElementById('listUl').innerHTML = html;
			document.getElementById('listUl').style.display = '';
			document.getElementById('listEmpty').style.display = 'none';
		}
		
		document.getElementById('listCount').innerHTML = performances.length;
		document.getElementById('listPageCurrent').innerHTML = time + '시 ~ ' + (time + 2) + '시';
	}

	function refresh(day) {
		day_add = day;
		getPerformanceListForMap();
	}
	function move(amount) {
		var result = amount + time;
		if (result < 0 || result > 22)
			return;
		
		time = result;
		getPerformanceListForMap();
	}
	
	function getPerformanceListForMap()
	{
		var url = "http://gilstar.com/gilstar/Performance.jsp";
		var obj = new Object();
		obj.req = "GET_PERFORMANCE_FROM_LIST";
		req = obj.req;
		obj.time = time;
		obj.day_add = day_add;
		obj.latitude = latitude;
		obj.longitude = longitude;
		
		getJSON(url, obj);
	}

	function replacer(key, value) 
	{
	    if (typeof value === 'number' && !isFinite(value)) 
	    {
	        return String(value);
	    }
	    return value;
	}
	
	function encodeURL(str){
	    var s0, i, s, u;
	    s0 = "";                // encoded str
	    for (i = 0; i < str.length; i++)
	    {
	        s = str.charAt(i);
	        u = str.charCodeAt(i);          // get unicode of the char
	        if (s == " ")
	        {
	        	s0 += "20";	// SP should be converted to "+"
	        }
	        else 
	        {
                if ((u >= 0x0) && (u <= 0x7f))    // single byte format
                {
                    s = "0"+u.toString(16);
                    s0 += s.substr(s.length-2);
                }
                else if (u > 0x1fffff)	// quaternary byte format (extended)
                {    
                    s0 += (oxf0 + ((u & 0x1c0000) >> 18)).toString(16);
                    s0 += (0x80 + ((u & 0x3f000) >> 12)).toString(16);
                    s0 += (0x80 + ((u & 0xfc0) >> 6)).toString(16);
                    s0 += (0x80 + (u & 0x3f)).toString(16);
                }
                else if (u > 0x7ff)	// triple byte format
                {        
                    s0 += (0xe0 + ((u & 0xf000) >> 12)).toString(16);
                    s0 += (0x80 + ((u & 0xfc0) >> 6)).toString(16);
                    s0 += (0x80 + (u & 0x3f)).toString(16);
                }
                else 			// double byte format
                {                      
                    s0 += (0xc0 + ((u & 0x7c0) >> 6)).toString(16);
                    s0 += (0x80 + (u & 0x3f)).toString(16);
                }
	        }
	    }

	    return s0;
	}
	
	//]]>
	</script>

<!-- 목록 보기 -->
<section id="list">

        <h1 class="hidden">목록 보기</h1>

		<div class="viewOption">
			<ul class="listDate">
			<li id="listDate_0" class="listDateLi listDateLiSelected"><a href="#" class="listDateA" onclick="refresh('0');return false;">오늘</a></li>
			<li id="listDate_1" class="listDateLi"><a href="#" class="listDateA" onclick="refresh('1');return false;">내일</a></li>
			</ul>
			<label for="setLocation" class="hidden">위치설정</label>
			<select id="setLocation" class="setLocation" onchange="hotSpot(this.value);">
			<option selected>내 주변</option>
			<option>홍대</option>
			<option>대학로</option>
			<option>강남</option>
			<option>대구</option>
			<option>부산</option>
			</select>
		</div>

        <div class="listInfo">
                <p class="listNum">총 <span id="listCount">0</span>개의 공연이 검색됨</p>
                <div class="listOrder listOrderSelTime" id="listOrder">
                        <a href="#" class="listOrderDistance" id="listOrderDistance" onclick="sort('D');return false;">거리순</a>
                        <a href="#" class="listOrderTime" id="listOrderTime" onclick="sort('T');return false;">시간순</a>
                        <div class="listOrderSel"></div>
                </div>
        </div>

        <ul class="listUl" id="listUl">
        </ul>
        <p class="listEmpty" id="listEmpty">공연이 없습니다.</p>

        <div class="listPage">
                <div class="listPageWrap">
                        <a href="#" class="listPagePrev" onclick="move(-2);return false;">이전시간</a>
                        <span class="listPageCurrent" id="listPageCurrent">17시 ~ 18시</span>
                        <a href="#" class="listPageNext" onclick="move(2);return false;">다음시간</a>
                </div>
        </div>

</section>
<!-- //목록 보기 -->

<?php include 'footer.php'; ?>